package codec

import (
	"io"

	"gitee.com/zwczou/lnet"
)

type PacketProtocol struct {
}

func Packet() *PacketProtocol {
	return &PacketProtocol{}
}

func (p *PacketProtocol) NewCodec(rw io.ReadWriter) (lnet.Codec, error) {
	codec := &packetCodec{
		p:      p,
		reader: rw,
		writer: rw,
	}
	codec.closer, _ = rw.(io.Closer)
	return codec, nil
}

type packetCodec struct {
	p      *PacketProtocol
	closer io.Closer
	reader io.Reader
	writer io.Writer
}

func (c *packetCodec) Receive(msg interface{}) error {
	_, err := msg.(io.ReaderFrom).ReadFrom(c.reader)
	return err
}

func (c *packetCodec) Send(msg interface{}) error {
	_, err := msg.(io.WriterTo).WriteTo(c.writer)
	return err
}

func (c *packetCodec) Close() error {
	if c.closer != nil {
		return c.closer.Close()
	}
	return nil
}
